﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using CRM_MList_from_CSV.CrmSdkService;

namespace CRM_MList_from_CSV
{
    public partial class MainForm : Form
    {
        //globální proměnné
        string InitFolder;
        List<string> list = new List<string>();
        CrmService service = new CrmService();

        public MainForm()
        {
            InitializeComponent();
            //nastavení výchozího adresáře
            InitFolder = GetInitFolder();
            textBoxInputFileName.Text = InitFolder;
            //zvýraznění tlačítka pro výběr souboru
            buttonSelectInputFile.BackColor = SystemColors.ButtonHighlight; ;
            labelInfo.Text = "Select the input file and create" + Environment.NewLine +
                "marketing list from it." + Environment.NewLine + Environment.NewLine +
                "Just follow the button color..." + Environment.NewLine +
                "easy peasy :-)" + Environment.NewLine + Environment.NewLine +
                "© 2015 Věroslav Olič";
            //vytvoření CRM služby
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType = 0; // ověřit se přes AD
            token.OrganizationName = Properties.Settings.Default.CRMOrgName;

            service.Url = Properties.Settings.Default.CRM_MList_from_CSV_CrmSdkService_CrmService;
            service.CrmAuthenticationTokenValue = token;
            service.Credentials = System.Net.CredentialCache.DefaultCredentials;
        }

        private void buttonSelectInputFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFile = new OpenFileDialog();
            OpenFile.InitialDirectory = GetInitFolder();
            OpenFile.RestoreDirectory = true;

            if (OpenFile.ShowDialog() == DialogResult.OK)
            {
                Stream stream = null;
                if ((stream = OpenFile.OpenFile()) != null)
                {
                    //zobrazit zvolený soubor
                    textBoxInputFileName.Text = OpenFile.FileName;
                    textBoxInputFileName.Refresh();
                    //uložit zvolený adresář
                    Properties.Settings.Default.LastOpenFolder = Path.GetDirectoryName(OpenFile.FileName);
                    Properties.Settings.Default.Save();
                    using (stream)
                    {
                        StreamReader reader = new StreamReader(stream);
                        int counter = 0;
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            list.Add(line);
                            counter++;
                        }
                        labelNumberCount.Text = counter.ToString();
                    }
                    listBoxFilePreview.Items.Clear();
                    foreach (string item in list)
                    {
                        listBoxFilePreview.Items.Add(item);
                    }
                    //změna zvýraznění na tlačítko tvorby MListu
                    buttonSelectInputFile.BackColor = SystemColors.Control;
                    buttonCreateMList.BackColor = SystemColors.ButtonHighlight;
                }
            }
        }
        private string GetInitFolder()
        {
            if (String.IsNullOrEmpty(Properties.Settings.Default.LastOpenFolder))
            {
                return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }
            else
            {
                return Properties.Settings.Default.LastOpenFolder;
            }
        }

        private void buttonCreateMList_Click(object sender, EventArgs e)
        {
            if (list.Count > 0)
            {
                //převod string na Guid
                List<Guid> listGuid = new List<Guid>();
                try
                {
                    foreach (string item in list)
                    {
                        listGuid.Add(Guid.Parse(item));
                    }
                }
                catch (ArgumentNullException)
                {
                    MessageBox.Show("Null input");
                    return;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Bad format of input GUID");
                    return;
                }
                //vytvoření MListu
                FormWorking WorkingForm = new FormWorking();
                WorkingForm.ControlBox = false;
                WorkingForm.StartPosition = FormStartPosition.CenterParent;
                WorkingForm.Show();
                WorkingForm.Refresh();

                list MList = new list();
                MList.listname = CreateName();
                MList.description = "Created by CRM MList application";
                MList.createdfromcode = new Picklist();
                MList.createdfromcode.Value = 1; //List of Accounts viz ListType Class
                Guid MListGuid = service.Create(MList);
                AddMemberListRequest addRequest = new AddMemberListRequest();
                addRequest.ListId = MListGuid;
                string allResponses = "";
                int counter = 1;
                foreach (Guid g in listGuid)
                {
                    addRequest.EntityId = g;
                    AddMemberListResponse response = (AddMemberListResponse)service.Execute(addRequest);
                    allResponses += counter.ToString() + " : " + response.Id.ToString() + Environment.NewLine;
                    counter ++;
                }
                WorkingForm.Close();
                FormResults ResultsForm = new FormResults();
                //pro tuhle referenci musí být textbox na ResultForm public nebo internal
                ResultsForm.StartPosition = FormStartPosition.CenterParent;
                ResultsForm.textBoxResults.Text = allResponses;
                ResultsForm.textBoxResults.SelectionStart = ResultsForm.textBoxResults.Text.Length;
                ResultsForm.textBoxResults.SelectionLength = 0;
                ResultsForm.Show();
                ResultsForm.textBoxResults.ScrollToCaret();
                ResultsForm.Refresh();
            }
            else
            {
                MessageBox.Show("No GUIDs in the list.","Warning",MessageBoxButtons.OK);
            }
        }

        private string CreateName()
        {
            if (textBoxName.Text.Length > 0)
            {
                return textBoxName.Text + " " + DateTime.Now.ToString();
            }
            else
            {
                return Environment.UserName + " " + DateTime.Now.ToString();
            }
        }
    }
}
